"""
管理端认证路由
"""
from flask import Blueprint, request
from flask_jwt_extended import (
    create_access_token,
    jwt_required,
    get_jwt_identity
)
from flask import current_app
from models import db, User
from utils import ApiResponse

auth_bp = Blueprint('auth', __name__, url_prefix='/admin/auth')


@auth_bp.route('/register', methods=['POST'])
def register():
    """管理员注册"""
    try:
        data = request.get_json()
        if not data:
            return ApiResponse.error(msg='请输入注册信息', code=400)

        # 验证必填字段
        required_fields = ['username', 'full_name', 'password']
        for field in required_fields:
            if field not in data or not data[field]:
                return ApiResponse.error(msg=f'{field} 是必填项', code=400)

        # 检查用户名是否已存在
        if User.query.filter_by(username=data['username']).first():
            return ApiResponse.error(msg='用户名已存在', code=400)

        # 创建用户
        user = User(
            username=data['username'],
            full_name=data['full_name'],
            email=data.get('email', ''),
        )
        user.set_password(data['password'])

        db.session.add(user)
        db.session.commit()

        return ApiResponse.success(
            data={
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'fullName': user.full_name
            },
            msg='注册成功',
            code=201
        )
    except Exception as e:
        db.session.rollback()
        return ApiResponse.error(msg=f'注册失败: {str(e)}', code=500)


@auth_bp.route('/login', methods=['POST'])
def login():
    """管理员登录"""
    try:
        data = request.get_json()
        if not data:
            return ApiResponse.error(msg='请输入账号密码', code=400)

        username = data.get('username')
        password = data.get('password')

        if not username or not password:
            return ApiResponse.error(msg='用户名和密码不能为空', code=400)

        user = User.query.filter_by(username=username).first()

        if not user or not user.verify_password(password):
            return ApiResponse.error(msg='账号密码错误', code=401)

        access_token = create_access_token(
            identity=user.username,
            expires_delta=current_app.config['JWT_ACCESS_TOKEN_EXPIRES']
        )

        return ApiResponse.success(
            data={
                'accessToken': access_token,
                'user': {
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'fullName': user.full_name
                }
            },
            msg='登录成功'
        )
    except Exception as e:
        return ApiResponse.error(msg=f'登录失败: {str(e)}', code=500)


@auth_bp.route('/logout', methods=['POST'])
@jwt_required()
def logout():
    """管理员登出"""
    try:
        return ApiResponse.success(msg='登出成功')
    except Exception as e:
        return ApiResponse.error(msg=f'登出失败: {str(e)}', code=500)


@auth_bp.route('/info', methods=['GET'])
@jwt_required()
def get_user_info():
    """获取当前登录用户信息"""
    try:
        username = get_jwt_identity()
        user = User.query.filter_by(username=username).first()
        
        if not user:
            return ApiResponse.error(msg='用户不存在', code=404)
        
        return ApiResponse.success(
            data={
                'id': user.id,
                'username': user.username,
                'email': user.email,
                'fullName': user.full_name,
                'createdAt': user.created_at.strftime('%Y-%m-%d %H:%M:%S') if user.created_at else None
            }
        )
    except Exception as e:
        return ApiResponse.error(msg=str(e), code=500)

